<?php

namespace app\modules\agent\controllers;

use app\components\Func;
use app\models\AuthAccount;
use app\models\AuthComment;
use app\models\AuthItem;
use app\models\AuthMessage;
use app\models\BuyerCashback;
use app\models\PayOrder;
use app\models\Video;
use app\modules\agent\AdminController;
use Yii;
use AlibabaCloud\Sts\Sts;
use AlibabaCloud\Client\AlibabaCloud;

class AjaxController extends AdminController
{
    //修改返现状态
    public function actionCashbackUpdate(){
        $cashback_id = Yii::$app->request->post('cashback_id',0);
        $state = Yii::$app->request->post('state',0);
        $cashback = BuyerCashback::findOne($cashback_id);
        if(empty($cashback)){
            throw new \Exception('参数错误', 1);
        }
        if($cashback->authShop->uid != Yii::$app->user->id){
            throw new \Exception('无权限', 1);
        }
        $cashback->state=$state;
        $cashback->save();

        return $this->success();
    }
    //回复私信
    public function actionMessageReply(){
        $id = Yii::$app->request->post('comment_id',0);
        $content = Yii::$app->request->post('content','');
        if(empty($content)){
            throw new \Exception('内容为空', 1);
        }
        $obj = AuthMessage::findOne($id);
        if(empty($obj)){
            throw new \Exception('参数错误', 1);
        }
        if($obj->authAccount->uid != Yii::$app->user->id){
            throw new \Exception('无权限', 1);
        }
        $obj->reply($content);
        return $this->success();
    }
    //回复评论
    public function actionCommentReply(){
        $id = Yii::$app->request->post('comment_id',0);
        $content = Yii::$app->request->post('content','');
        if(empty($content)){
            throw new \Exception('内容为空', 1);
        }
        $obj = AuthComment::findOne($id);
        if(empty($obj)){
            throw new \Exception('参数错误', 1);
        }
        if($obj->authAccount->uid != Yii::$app->user->id){
            throw new \Exception('无权限', 1);
        }
        $content = strip_tags($content);
        $obj->commentReply($content);
        return $this->success();
    }
    /**
     * 更新用户所有授权账号信息
     * 20201015
     */
    public function actionUpdateAllAuthAccountBaseInfo()
    {
        Func::exec('auth-account/update-all-base-info',[Yii::$app->user->id]);
        return $this->success();
    }
    /**
     * 同步更新用户的关注和粉丝
     * 20200915
     */
    public function actionSyncFollowFans()
    {
        $id = Yii::$app->request->post('aid',0);
        $obj = AuthAccount::findOne($id);
        if(empty($obj)){
            throw new \Exception('参数错误', 1);
        }
        if($obj->uid != Yii::$app->user->id){
            throw new \Exception('无权限', 1);
        }
        Func::exec('auth-account/sync-follow-fans',[$id]);
        return $this->success();
    }
    /**
     * 同步更新拉取所有授权账号的数据
     * 20201010
     */
    public function actionSyncAllAuthAccountItems()
    {
        Func::exec('auth-account/sync-all-auth-account-items',[Yii::$app->user->id]);
        return $this->success();
    }
    /**
     * 同步更新所有账号最近几天的发布项目数据
     * 20201020
     */
    public function actionSyncAllAuthAccountItemsByLastDay()
    {
        $last_day = Yii::$app->request->post('last_day',0);
        $begin_time = strtotime(date('Ymd000000',(time()-$last_day*86400)));
        $end_time = strtotime(date('Ymd235959',time()));
        Func::exec('auth-account/sync-all-auth-account-items-by-time',[Yii::$app->user->id,$begin_time,$end_time]);
        return $this->success([$begin_time,$end_time]);
    }
    /**
     * 同步更新用户发布的所有项目
     * 20200915
     */
    public function actionSyncItems()
    {
        $id = Yii::$app->request->post('aid',0);
        $obj = AuthAccount::findOne($id);
        if(empty($obj)){
            throw new \Exception('参数错误', 1);
        }
        if($obj->uid != Yii::$app->user->id){
            throw new \Exception('无权限', 1);
        }
        Func::exec('auth-account/sync-items',[$id]);
        return $this->success();
    }
    /**
     * 同步更新单个项目
     * 20200915
     */
    public function actionSyncItem()
    {
        $item_id = Yii::$app->request->post('id',0);
        $obj = AuthItem::findOne($item_id);
        if(empty($obj)){
            throw new \Exception('参数错误', 1);
        }
        if($obj->authAccount->uid != Yii::$app->user->id){
            throw new \Exception('无权限', 1);
        }
        Func::exec('auth-item/sync-item',[$item_id]);
        return $this->success();
    }
    /**
     * 发布项目
     * 20200915
     */
    public function actionPublish(){
        $this->checkPoint();
        $str = file_get_contents("php://input");
        $arr = json_decode($str,1);
        foreach ($arr as $row){
            if(empty($row)) continue;
            $obj = new AuthItem();
            $obj->auth_app_id = $row['auth_app_id'];
            $obj->auth_account_id = $row['auth_account_id'];
            $obj->video_id = $row['video_id'];
            $obj->title = $row['title'];
            $obj->create_time = time();
            $obj->post_time = $row['timing'] == 1 ? intval(strtotime($row['post_time'])) : time();
            $obj->timing = $row['timing'];
            $obj->state = $row['timing'] == 1 ? AuthItem::STATE_PUBLISH_WAIT : AuthItem::STATE_PUBLISHING;
            if(!$obj->save()){
                throw new \Exception(json_encode($obj->getErrors()));
            }
            $authAccount = $obj->authAccount;
            $authAccount->incrAuthItemNums(1);
            $authAccount->last_auth_item_id = $obj->id;
            $authAccount->last_auth_item_time = time();
            if(!$authAccount->save()){
                throw new \Exception(json_encode($authAccount->getErrors()));
            }
            if($row['timing'] != 1){
                Func::exec('auth-item/publish-item',[$obj->id]);
            }
        }
        return $this->success();
    }
    /**
     * 同步单个项目评论
     * 20200920
     */
    public function actionSyncComment()
    {
        $item_id = Yii::$app->request->post('id',0);
        $authItem = AuthItem::findOne($item_id);
        if(empty($authItem)){
            throw new \Exception('参数错误', 1);
        }
        if($authItem->authAccount->uid != Yii::$app->user->id){
            throw new \Exception('无权限', 1);
        }
        Func::exec('auth-item/sync-comments',[$item_id]);
        return $this->success();
    }


    //上传视频信息
    public function actionUploadVideoInfo(){
        $store = Yii::$app->request->post('store',1);
        $filename = Yii::$app->request->post('filename','');
        $title = Yii::$app->request->post('title','');
        $size = Yii::$app->request->post('size',0);
        $duration = Yii::$app->request->post('duration',0);
        $wx_uid = Yii::$app->user->id;
        $video = Video::makeObjByUploadInfo($wx_uid,$store,$filename,$title,$size,$duration);
        return $this->success([
            'id'=>$video->id,
            'filename'=>$video->getStoreFile(1)
        ]);
    }
    //生成充值支付二维码
    public function actionBuildPayQr($total_fee){
        if(!in_array($total_fee,[100,5000,10000,20000,50000])){
            throw new \Exception('支付金额错误',1);
        }
        $order = new PayOrder();
        $order->uid=Yii::$app->user->id;
        $order->pay_account_id=1;
        $order->total_fee=$total_fee;
        $order->body='购买'.$total_fee.'积分';
        $order->ctime=time();
        if(!$order->save()){
            throw new \Exception(json_encode($order->getErrors()));
        }
        $arr = $order->payAccount->getPayObj()->buildNativeQr2($order);
        $arr['pay_order_id'] = $order->id;
        return $this->success($arr);
    }
    //阿里云STS授权
    public function actionAliSts(){
        //构建阿里云client时需要设置AccessKey ID和AccessKey Secret
        AlibabaCloud::accessKeyClient(Yii::$app->params['oss_sts_access_key'], Yii::$app->params['oss_sts_access_secret'])
            ->regionId(Yii::$app->params['oss_sts_region_id'])
            ->asDefaultClient();

        $res = Sts::v20150401()
            ->assumeRole()
            //指定角色ARN
            ->withRoleArn(Yii::$app->params['oss_sts_role_arn'])
            //RoleSessionName即临时身份的会话名称，用于区分不同的临时身份
            ->withRoleSessionName('external-username')
//            ->withRoleSessionName(Yii::$app->user->id)
            //设置权限策略以进一步限制角色的权限
            //以下权限策略表示拥有所有OSS的只读权限
            ->withPolicy('{
             "Statement":[
                {
                     "Action":
                 [
                     "oss:*"
                     ],
                      "Effect": "Allow",
                      "Resource": "*"
                }
                   ],
          "Version": "1"
        }')
            ->connectTimeout(60)
            ->timeout(65)
            ->request();
        $arr = $res->get('Credentials');
        $arr['bucket'] = Yii::$app->params['oss_bucket'];
        $arr['region'] = Yii::$app->params['oss_sts_region_id'];
//        print_r($arr);
        return $this->success($arr);
    }
    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub
        set_exception_handler([$this, 'error']);

    }

    //统一报错AJAX
    public function error(\Throwable $e){
        $errmsg = $e->getMessage();
        if(YII_DEBUG){
            $errmsg.=$e->getFile().$e->getLine();
        }
        else{
            Yii::error($errmsg.$e->getFile().$e->getLine());
        }
        echo json_encode(['errcode'=>$e->getCode(),'errmsg'=>$errmsg],JSON_UNESCAPED_UNICODE);
//        return json_encode(['errcode'=>$e->getCode(),'errmsg'=>$errmsg],JSON_UNESCAPED_UNICODE);
    }
    //统一成功JAX
    public function success($arr = []){

//        header("Access-Control-Allow-Origin: *");
//        header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
//        header('Access-Control-Allow-Headers:x-requested-with,content-type');
        return json_encode(array_merge(['errcode'=>0,'errmsg'=>'','result'=>$arr]),JSON_UNESCAPED_UNICODE);
    }

}
